import os
import time

# 前提条件：电脑可以正常使用adb命令
def read_wm_size():
    fun = os.popen('adb shell wm size')
    fun_read = fun.readline()
    wm_xy = fun_read.split(':')[1].strip().split('x')
    wm_x = int(wm_xy[0])
    wm_y = int(wm_xy[1])
    print('屏幕物理尺寸的x：', wm_x)
    print('屏幕物理尺寸的y：', wm_y)
    return wm_x, wm_y


def read_getevent():
    fun = os.popen('adb shell getevent -c 10')
    #fun = os.popen('adb shell getevent')
    print('请点击需要读取的屏幕位置')
    fun_read = []  # is list
    while fun_read == []:
        fun_read = fun.readlines()
        time.sleep(0.1)
    # print(fun_read)

    # to string
    str = ''.join(fun_read)
    # print(str)
    get_x_position = str.find('0035')
    get_x = str[get_x_position + 5:get_x_position + 5 + 8]
    get_y_position = str.find('0036')
    get_y = str[get_y_position + 5:get_y_position + 5 + 8]
    # to DEC
    dec_x = int(get_x.upper(), 16)
    dec_y = int(get_y.upper(), 16)
    print('点击的点的像素x:', dec_x)
    print('点击的点的像素y:', dec_y)
    # print('35 and 36:',get_x_position,get_y_position)
    # /dev/input/event2
    get_device_35_36_str = str[get_x_position + 5 + 9:get_y_position - 7]
    #print('between 35-36:', get_device_35_36_str)

    get_device_index = str.find(get_device_35_36_str)
    get_device_name = str[get_device_index-14:get_device_index-2].strip()
    #print('device name:', get_device_name)

    return dec_x, dec_y, get_device_name


def get_max():
    dec_x, dec_y, get_device_name = read_getevent()
    #print('1111:', get_device_name)
    # get_device_name='add device 2'

    fun = os.popen('adb shell getevent -p')
    fun_read = fun.readlines()

    str = ''.join(fun_read)

    get_mark = str.find(get_device_name)

    mark_str = str[get_mark:]
    # print(mark_str)

    get_x1_position = mark_str.find('0035')
    get_x2_position = mark_str.find('0036')
    get_x1 = mark_str[get_x1_position + 4:get_x2_position]
    get_x1_max = get_x1[get_x1.find('max'):]
    get_x1_max_1 = get_x1_max.find(',')  # get_x1_max_1=8
    get_x_max = int(get_x1_max[3:get_x1_max_1].strip())+1
    print('屏幕像素点最大值x:', get_x_max)

    get_y1_position = mark_str.find('0036')
    get_y2_position = mark_str.find('0039')
    get_y1 = mark_str[get_y1_position + 4:get_y2_position]
    get_y1_max = get_y1[get_y1.find('max'):]
    get_y1_max_1 = get_y1_max.find(',')  # get_x1_max_1=8
    get_y_max = int(get_y1_max[3:get_y1_max_1].strip())+1
    print('屏幕像素点最大值y:', get_y_max)
    return get_x_max, get_y_max,dec_x, dec_y



if __name__ == '__main__':
    # 计算公式：(touch_size * wm_size / max)
    wm_x, wm_y = read_wm_size()
    get_x_max, get_y_max,dec_x, dec_y= get_max()
    #dec_x, dec_y ,get_device_name= read_getevent()
    x = int(dec_x * wm_x / get_x_max)
    y = int(dec_y * wm_y / get_y_max)

    print('x 坐标是: ', x)
    print('y 坐标是: ', y)